<script>
  import TreeSelect from '@/components/common/tree-select';
  import RightToolBar from "@/components/common/right-toolbar";
  import SaveUpdate from "@/components/multi-dict/save-update";
  export default {
    layout: 'admin',
    components: {
      TreeSelect, RightToolBar, SaveUpdate
    },
    data() {
      return {
        // 客户端初始化
        clientInit: true,
        // 级联字典列表
        multiDictList: [],
        // 级联字典总数
        totalNum: 0,
        // 级联字典树
        multiDictTree: [],
        // 类型枚举列表
        typeEnumList: [],
        // 默认状态枚举列表
        defaultStatusEnumList: [
          {
            value: 0,
            name: '是'
          },
          {
            value: 1,
            name: '否'
          }
        ],
        // 状态枚举列表
        statusEnumList: [
          {
            value: 0,
            name: '可用'
          },
          {
            value: 1,
            name: '禁用'
          }
        ],
        // 商店检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 商店检索表单对象
        searchForm: {
          // 字典名称
          word: '',
          // 父级字典
          parentId: undefined,
          // 类型
          type: undefined,
          // 默认状态[0-是 1-否]
          defaultStatus: undefined,
          // 状态
          status: undefined,
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
    },
    filters: {
      /**
       * 状态名称映射
       * @param {number} value              状态值
       * @param {Array<{name,value}>} list  枚举列表
       */
      statusFormat(value, list) {
        if (!value && value !== 0) {
          return '';
        }
        for (let item of list) {
          if (item.value === value) {
            return item.name;
          }
        }
        return '';
      },
      /**
       * 默认状态名称映射
       * @param {number} value              默认状态值
       * @param {Array<{name,value}>} list  枚举列表
       */
      defaultStatusFormat(value, list) {
        if (!value && value !== 0) {
          return '';
        }
        for (let item of list) {
          if (item.value === value) {
            return item.name;
          }
        }
        return '';
      }
    },
    async asyncData({ app, error }) {
      // 客户端调用直接返回
      if (process.client) return {};
      const searchForm = {
        page: 1,
        limit: 10
      }
      let res;
      try {
        res = await app.$axios.$post('/multi-dict/page/list', searchForm)
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      let data = res.data;
      const multiDictList= data.data;
      const totalNum= data.totalNum;

      try {
        res = await app.$axios.$get('/multi-dict/enums')
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      data = res.data;
      const multiDictTree = data.multiDictTree;
      const typeEnumList = data.typeEnumList;

      return {
        clientInit: false,
        multiDictList: multiDictList,
        totalNum: totalNum,
        multiDictTree: multiDictTree,
        typeEnumList: typeEnumList
      }
    },
    created() {
      if (process.client) {
        if (this.clientInit) {
          // 客户端加载
          this.loadPage();
        }
      }
    },
    methods: {
      /**
       * 加载页面数据方法
       */
      loadPage() {
        this.getMultiDictList();
        this.getMultiDictEnum();
      },
      /**
       * 获取级联字典列表
       */
      getMultiDictList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/multi-dict/page/list', this.searchForm)
          .then(({ data }) => {
            this.multiDictList = data.data;
            this.totalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 结束加载
            this.dataLoad = false;
          });
      },
      /**
       * 获取级联字典枚举方法
       */
      getMultiDictEnum() {
        this.$axios.$get('/multi-dict/enums')
          .then(({ data }) => {
            this.multiDictTree = data.multiDictTree;
            this.typeEnumList = data.typeEnumList;
          })
          .catch(() => {});
      },
      /**
       * 商店检索事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getMultiDictList();
      },
      /**
       * 选中父级节点事件
       * @param {Object} node 父级节点对象
       */
      changeParentMultiDictHandle(node) {
        const searchForm = this.searchForm;
        searchForm.parentId = node.id;
      },
      /**
       * 重置检索表单事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getMultiDictList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getMultiDictList();
      },
      /**
       * 打开新增/修改弹出框事件
       * @param {boolean} optType         操作类型[true-修改 false-添加]
       * @param {Object}  multiDict       级联字典对象
       * @param {Object}  parentMultiDict 父级级联字典对象
       */
      openSaveUpdateDialogHandle(optType, multiDict, parentMultiDict) {
        this.$refs.saveUpdateDialog.openDialog(optType, multiDict, parentMultiDict);
      },
      /**
       * 修改级联字典状态事件
       * @param {Object} multiDict 级联字典对象
       * @param {number} status    状态值
       */
      updateStatusHandle(multiDict, status) {
        let promise = Promise.resolve();
        if (status === 1) {
          promise = this.$confirm(
            `您确定要停用【${multiDict.name}】字典吗？`,
            '操作提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
        }
        promise
          .then(() => {
            this.buttonLoad = true;

            let body = {
              idList: [ multiDict.id ],
              status
            }
            return this.$axios.$post('/multi-dict/update/status', body);
          })
          .then(() => {
            this.notify('success', '操作成功', `${status === 0 ? '启用' : '停用'}级联字典成功`);

            multiDict.status = status;
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          })
      },
      /**
       * 删除事件
       * @param {Object} multiDict 级联字典对象
       */
      deleteHandle(multiDict) {
        this.$confirm(
          `您确定要删除【${multiDict.name}】${multiDict.children ? '及其子' : ''}字典吗？`,
          '操作提示',
          {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'danger'
          })
          .then(() => {
            this.buttonLoad = true;

            const body = {
              id: multiDict.id
            }
            return this.$axios.$delete('/multi-dict/delete', { data: body });
          })
          .then(() => {
            this.notify('success', '操作成功', '删除级联字典成功');
            // 重新加载页面数据
            this.loadPage();
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          });
      }
    }
  }
</script>

<template>
  <div class="multi-dict-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm"
               @keyup.enter.native="searchHandle">
        <el-form-item prop="word" label="级联字典检索">
          <el-input v-model="searchForm.word" clearable placeholder="请输入级联字典名称"></el-input>
        </el-form-item>
        <el-form-item prop="type">
          <el-select v-model="searchForm.type" clearable placeholder="请选择类型">
            <el-option v-for="typeEnum in typeEnumList" :key="'typeEnum' + typeEnum.value"
                       :label="typeEnum.name" :value="typeEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="parentId">
          <tree-select form-size="mini" :data-obj="searchForm" prop-key="parentId" node-key="id"
                       :tree-data="multiDictTree" :width="400" placeholder="请选择父级字典" class-name="multi-dict-tree"
                       @node-click="changeParentMultiDictHandle" />
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="m-d-tool">
      <el-button :disabled="dataLoad" @click="openSaveUpdateDialogHandle(false, undefined, undefined)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getMultiDictList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="列表加载中"
      element-loading-spinner="el-icon-loading"
      :data="multiDictList"
      row-key="id"
    >
      <el-table-column prop="name" label="字典名称"></el-table-column>
      <el-table-column prop="typeName" label="类型"></el-table-column>
      <el-table-column prop="sort" label="排序等级"></el-table-column>
      <el-table-column prop="defaultStatus" label="默认状态">
        <template v-slot="{ row }">
          {{ row.defaultStatus | defaultStatusFormat(defaultStatusEnumList) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" >
        <template v-slot="{ row }">
          {{ row.status | statusFormat(statusEnumList) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="createUser" label="创建用户" align="center"></el-table-column>
      <el-table-column
        header-align="left"
        width="140"
        label="操作">
        <template v-slot="{ row }">
          <el-button type="text" icon="el-icon-plus"
                     @click="openSaveUpdateDialogHandle(false, undefined, row)">
            新增
          </el-button>
          <el-dropdown :disabled="dataLoad || buttonLoad">
            <span class="el-dropdown-link fz12" :style="{ color: themeColor, marginLeft: '7px' }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-s-operation"
                                @click.native="openSaveUpdateDialogHandle(true, row, undefined)">
                编辑
              </el-dropdown-item>
              <el-dropdown-item v-show="row.status === 1" icon="el-icon-check"
                                @click.native="updateStatusHandle(row, 0)">
                启用
              </el-dropdown-item>
              <el-dropdown-item v-show="row.status === 0" icon="el-icon-close"
                                @click.native="updateStatusHandle(row, 1)">
                停用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteHandle(row)" class="danger-color">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 新增/修改弹出框 -->
    <save-update @refresh="loadPage" ref="saveUpdateDialog" />
  </div>
</template>

<style scoped>
  .multi-dict-page >>> .multi-dict-tree {
    width: 200px;
  }
  .multi-dict-page .m-d-tool {
    margin-bottom: 7px;
  }
  .multi-dict-page .paging {
    text-align: right;
    margin: 7px;
  }
</style>
